import React, { Component } from "react";
import { Button, Modal, Form, Drawer, PageHeader, Divider, Badge } from "antd";
import "@/assets/css/settings";
import { BasicLayout, BasicLayoutSearch } from "../../components/BasicLayout";
import {
  BasicPagination,
  compareNum,
  TableCustomize,
  openSuccessModal,
  openModalMessage,
  compareString,
} from "../../components/TableCustomize";
import { withPermission } from "../../components/withpermission";
import SearchForm from "./SearchFormDetails";
import * as BomService from "../../axios/Bom";
import * as APIService from "../../axios/api";
import * as APIServicePX from "../../axios/api_px";
import { withRouter } from "react-router";
import Examine from "./Examine";
import AddDetailForm from "./AddDetailForm";
const CreateButton = withPermission(Button, "create");

class Bom_details extends Component {
  state = {
    dataSource: [],
    visible: false,
    advanced: false,
    searchItem: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: "序号",
        dataIndex: "id",
        width: 50,
        align: "center",
        render: (text, record, index) => (
          <span>
            {(this.state.pageNum - 1) * this.state.pageSize + index + 1}
          </span>
        ),
      },

      {
        title: "物料编码",
        width: 150,
        editable: true,
        dataIndex: "partCode",
        sorter: (a, b) => compareString(a.partCode, b.partCode),
        render: (text, record, index) => (
          <div>
            {record.partChangeAttitude == 1 ? (
              <Badge status="success" text={"新增"} />
            ) : record.partChangeAttitude == 2 ? (
              <Badge status="default" text={"取消"} />
            ) : record.partChangeAttitude == 3 ? (
              <Badge status="warning" text={"属性变化"} />
            ) : record.partChangeAttitude == 4 ? (
              <Badge status="processing" text={"回仓"} />
            ) : null}
            <div>{text}</div>
          </div>
        ),
      },
      {
        title: "图号",
        width: 150,
        // allowEllipsis: true,
        dataIndex: "paperCode",
        sorter: (a, b) => compareString(a.paperCode, b.paperCode),
      },
      {
        title: "机型",
        width: 140,
        dataIndex: "model",
        sorter: (a, b) => compareString(a.model, b.model),
      },
      {
        title: "物料名称",
        width: 130,
        editable: true,
        dataIndex: "partName",
        sorter: (a, b) => compareString(a.partName, b.partName),
      },
      {
        title: "物料规格",
        width: 170,
        editable: true,
        dataIndex: "partSpec",
        sorter: (a, b) => compareString(a.partSpec, b.partSpec),
      },
      {
        title: "数量",
        width: 80,
        dataIndex: "partNeedNum",
        editable: true,
        sorter: (a, b) => compareNum(a.partNeedNum, b.partNeedNum),
      },
      {
        title: "版本",
        width: 80,
        dataIndex: "version",
        sorter: (a, b) => compareString(a.version, b.version),
      },
      {
        title: "仓库",
        width: 100,
        editable: true,
        dataIndex: "storeName",
        sorter: (a, b) => compareString(a.storeName, b.storeName),
      },
      {
        title: "装配组别名称",
        width: 190,
        dataIndex: "assemblyGroup",
        editable: true,
        sorter: (a, b) => compareString(a.assemblyGroup, b.assemblyGroup),
      },
      {
        title: "装配组别代码",
        width: 150,
        dataIndex: "groupCode",
        editable: true,
        sorter: (a, b) => compareString(a.groupCode, b.groupCode),
      },
      {
        title: "依附关系和标准件",
        width: 300,
        dataIndex: "remark",
        sorter: (a, b) => compareString(a.remark, b.remark),
      },
      {
        title: "发料仓库",
        width: 150,
        dataIndex: "realityStoreName",
        sorter: (a, b) => compareString(a.realityStoreName, b.realityStoreName),
      },
      {
        title: "操作",
        width: 100,
        dataIndex: "opts",
        render: (text, record) => (
          <div>
            <a onClick={() => this.deletes(0, record)}>删除</a>
          </div>
        ),
      },
      { dataIndex: "999" },
    ],
    selectedRows: [],
    selectedRowKeys: [],
    locationData: {},
    searchItemFather: {},
    loading: false,
    downloadLoading: false,
    elseVersions: [],
    elseVersionsLens: 0,
    disabled: true,
    visible: false,
    formData: [],
    update: null,
    submitLoading: false,
    editData: {}, // 修改的原数据
    departmentList: [], // 部门列表
    warehouseList: [], // 仓库列表
    assemblyGroupList: [], // 装配组别
    printData: {}, // 打印数据
  };
  componentDidMount() {
    this.setState(
      {
        locationData: this.props.location.data
          ? this.props.location.data.record
          : JSON.parse(localStorage.getItem("Bom_detailsList")),
        searchItemFather: this.props.location.data
          ? this.props.location.data.searchItem
          : JSON.parse(localStorage.getItem("Bom_searchItem")),
      },
      this.fetch
    );
    this.getAssemblyGroup(); // 装配组别
    this.getDeptList();
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  getAssemblyGroup = () => {
    APIServicePX.queryAssemblyGroup()
      .then((res) => {
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        let assemblyGroupList = res.data.data;
        this.setState({ assemblyGroupList });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };

  // 获取部门/仓库
  getDeptList = () => {
    APIService.getDepartMents()
      .then((res) => {
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        let departmentList = res.data.data,
          warehouseList = [];
        for (let i in departmentList) {
          if (departmentList[i].name == "仓库") {
            warehouseList = departmentList[i].children;
          }
        }
        this.setState({ departmentList, warehouseList });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true });
    const { locationData, searchItem } = this.state;
    const data = { ...locationData, ...searchItem, pageNum, pageSize };
    // console.log('传的数据', data);
    BomService.productionOrderVersionDetail(data)
      .then((res) => {
        // console.log(res);
        this.setState({ loading: false });
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        this.setState({
          dataSource: res.data.data,
          total: res.data.total,
          pageNum,
          pageSize,
        });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };

  handleSearch = (value) => {
    console.log(value, 'handleSearch');
    // debugger
    // const { assemblyGroupList } = this.state;
    // let a = assemblyGroupList.find((e) => e.groupCode == value.assemblyGroup);
    // value.assemblyGroup = a?.groupName;
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced });
  };
  loadData = (value, dataSource) => {
    // console.log('当前行编辑数据', value, dataSource)
    BomService.alterBom(value).then((item) => {
      if (item.data.code !== 200) {
        openModalMessage("error", item.data.msg);
        return;
      }
      openSuccessModal(item.data.msg);
      this.fetch();
    });
  };
  exportProductDetailList = () => {
    const { locationData, searchItem } = this.state;
    console.log(locationData, searchItem, 'locationData, searchItem');
    let obj = {
      ...searchItem, "id": locationData.id, version: locationData.version
    }
    console.log(locationData, searchItem, obj, '-----------');

    Modal.confirm({
      title: "默认导出数据较多，需要较长时间，确认全部导出吗？",
      onOk() {
        BomService.exportProductDetailList(obj).then(
          (res) => {
            //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            let url = window.URL.createObjectURL(
              new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              })
            );
            // 创建A标签
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            // 设置的下载文件文件名
            const fileName = decodeURI("生产订单-详情页面");
            // 触发点击方法
            link.setAttribute("download", fileName);
            document.body.appendChild(link);
            link.click();
          }
        );
      },
      onCancel() { },
    });
  };
  onOk = () => {
    const { searchItem, disabled, update } = this.state;
    this.formPassToStock.validateFields((err, value) => {
      if (err) return;
      let data = {
        batchNo: update.batchNo,
        version: update.version,
        id: update.id,
      };
      // console.log(searchItem);
      // this.formSearch && this.formSearch.resetFields();
      this.setState(
        {
          // searchItem: data,
          searchItem: { ...searchItem, ...data},
          visible: false,
          locationData: update,
        },
        () => {
          this.fetch();
        }
      );
    });
  };
  handleCancel = () => {
    this.formDrawer && this.formDrawer.resetFields();
    this.setState({
      visible: false,
      drawerVisible: false,
      submitLoading: false,
    });
    this.fetch();
  };
  // 其他版本 点击切换    做个弹窗选择
  elseVersions = () => {
    // const { locationData, elseVersionsLens, disabled } = this.state;
    let item = JSON.parse(localStorage.getItem("Bom_detailsList"));
    // console.log('这是什么', item);
    // let data = locationData.batchNo
    // let data1 = locationData.version
    let data = item.batchNo;
    let data1 = item.version;
    BomService.produceImportHistoryList(data, data1)
      .then((res) => {
        // console.log(res);
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        this.setState({
          visible: true,
          formData: res.data.data,
        });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };
  // 还原
  restore = () => {
    const { locationData } = this.state;
    let data = locationData.batchNo;
    let data1 = locationData.version;
    BomService.restoreProduceImport(data, data1).then((value) => {
      // console.log(value);
      if (value.data.code !== 200) {
        openModalMessage("warning", value.data.msg);
        return;
      }
      locationData.isGrey = 0;
      let item = { batchNo: data, version: data1 };
      localStorage.setItem("Bom_detailsList", JSON.stringify(item));
      this.fetch();
      // this.setState({
      // 	locationData: JSON.parse(localStorage.getItem('Bom_detailsList')),
      // 	searchItem: JSON.parse(localStorage.getItem('Bom_searchItem'))
      // } )
    });
  };
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({ searchItem: {} }, this.fetch);
  };
  // 新增 0  修改 1
  add = (type, record = {}) => {
    this.setState({
      drawerVisible: true,
    });
    if (type == 1) {
      this.setState({
        drawerTitle: "修改",
        editData: { ...this.state.locationData, ...record },
      });
    } else {
      this.setState({
        drawerTitle: "新增",
        editData: { ...this.state.locationData },
      });
    }
  };

  onHandleOk = () => {
    this.formDrawer.validateFields((err, value) => {
      if (err) return;
      this.setState({ submitLoading: true });
      console.log(value);
      const { assemblyGroupList } = this.state;
      let a = assemblyGroupList.find((e) => e.groupCode == value.assemblyGroup);
      value.assemblyGroup = a?.groupName;

      BomService.addBom(value)
        .then((res) => {
          console.log(res);
          this.setState({ submitLoading: false });
          if (res.data.code !== 200) {
            openModalMessage("warning", res.data.msg);
            return;
          }
          openSuccessModal(res.data.msg);
          this.handleCancel();
        })
        .catch((err) => {
          openModalMessage("error", err.message);
          this.setState({ submitLoading: false });
        });
    });
  };
  // 删除
  deletes = (type, record = {}) => {
    console.log(type, record, "删除");
    const { selectedRowKeys } = this.state;
    let str = "";
    if (type == 1) {
      if (selectedRowKeys.length == 0) {
        openModalMessage("warning", "请选择物料");
        return;
      }
      for (let i in selectedRowKeys) {
        str += "&idList=" + selectedRowKeys[i];
      }
    } else {
      str = "idList=" + record.id;
    }

    let then = this;
    Modal.confirm({
      title: "确认删除所选物料?",
      onOk() {
        BomService.deleteBom(str).then((item) => {
          if (item.data.code === 200) {
            openSuccessModal("删除成功");
            then.fetch();
            return;
          }
          openModalMessage("error", item.data.msg);
        });
      },
      onCancel() { },
    });
  };

  //加法精准度
  accAdd = (arg1, arg2) => {
    var r1, r2, m;
    // console.log('arg1.toString()',arg1.toString().split(".")[1],'arg2.toString()',arg2.toString().split(".")[1])
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // console.log('arg1',r1,'arg2',r2,m)
    return (arg1 * m + arg2 * m) / m;
  };

  getPrintData = () => {
    const { selectedRows } = this.state;
    // if (selectedRows.length == 0) {
    //   openModalMessage("warning", "请选择物料");
    //   return;
    // }
    console.log(selectedRows, "selectedRows");

    let pageNum = 25;
    let numbers = [];
    let list = [];
    let pages = [];

    for (let i = 0; i < Math.ceil(selectedRows.length / pageNum); i++) {
      pages.push(i);
    }

    pages.map((pa) => {
      let number = 0;
      let arr = selectedRows.slice(pa * pageNum, (pa + 1) * pageNum);
      list.push(arr);
      arr.map((item) => {
        number = this.accAdd(item.partNeedNum, number);
      });
      numbers.push(number);
    });

    console.log(numbers, list, pages);
    let printData = { numbers, list, pages, pageNum };
    return printData;
  };

  // 打印
  print = () => {
    const { selectedRows } = this.state;
    if (selectedRows.length == 0) {
      openModalMessage("warning", "请选择物料");
      return;
    }

    let printData = this.getPrintData();
    console.log(printData, 'printData');
    this.setState({ printData }, () => {
      let printInnerHTML = document.getElementById("print_table").innerHTML;
      window.document.body.innerHTML = printInnerHTML;
      window.print();
      window.location.reload();
    });
  };

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      formData,
      disabled,
      locationData,
      loading,
      dataSource,
      advanced,
      columns,
      pageNum,
      pageSize,
      total,
      searchItemFather,
      searchItem,
      downloadLoading,
      drawerVisible,
      drawerTitle,
      submitLoading,
      editData,
      warehouseList,
      assemblyGroupList,
      printData,
    } = this.state;
    const rowSelection = {
      type: "checkbox",
      columnWidth: 40,
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        });
      },
    };
    return (
      <div>
        <BasicLayoutSearch>
          <PageHeader
            style={{ padding: "4px 24px" }}
            onBack={() =>
              this.props.history.push({
                pathname: "/Bom",
                data: searchItemFather,
              })
            }
            title={`${locationData.batchNo}详细数据`}
          ></PageHeader>
          <Divider />
          <SearchForm
            onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            resetForm={this.resetForm}
            assemblyGroupList={assemblyGroupList}
            ref={(node) => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <BasicLayout
          name={`${locationData.batchNo} 版本${locationData.version}`}
          icon="table"
          buttons={[
            // <Button key={1}>版本变更调序</Button>,
            <Button key={7} onClick={this.print} type="primary">
              打印
            </Button>,
            <Button key={5} onClick={this.add} type="primary">
              新增
            </Button>,
            // <Button key={6} onClick={() => this.deletes(1)}>批量删除</Button>,
            <Button key={2} onClick={this.elseVersions} type="primary">
              查看其他版本
            </Button>,
            <Button
              key={4}
              onClick={this.restore}
              type="primary"
              disabled={
                this.state.locationData.isGrey &&
                  this.state.locationData.isGrey === 1
                  ? false
                  : true
              }
            >
              还原
            </Button>,
            <Button
              key={3}
              onClick={this.exportProductDetailList}
              type="primary"
              icon="download"
            >
              导出
            </Button>,
          ]}
        >
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            scroll={{ x: true, y: 600 }}
            allowDrafting={true}
            rowClassName={(record, index) => {
              return [
                "editable-row",
                index % 2 === 0 ? "editable-row" : "editable-row12",
              ];
            }}
            allowEditable={this.loadData}
            rowSelection={rowSelection}
          />
          <BasicPagination
            pageNum={pageNum}
            pageSize={pageSize}
            total={total}
            loadData={this.fetch}
          />
        </BasicLayout>
        <Modal
          visible={visible}
          destroyOnClose
          title={"选择版本号"}
          onOk={this.onOk}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <Examine
            ref={(node) => (this.formPassToStock = node)}
            formData={formData}
            update={(data) => {
              this.setState({
                update: data,
              });
            }}
          />
        </Modal>
        <Drawer
          width={460}
          visible={drawerVisible}
          title={drawerTitle}
          onClose={this.handleCancel}
          maskClosable={false}
          destroyOnClose={true}
        >
          <AddDetailForm
            formData={editData}
            onOk={this.onHandleOk}
            ref={(node) => (this.formDrawer = node)}
            onClose={this.handleCancel}
            warehouseList={warehouseList}
            assemblyGroupList={assemblyGroupList}
          />
          <div
            style={{
              position: "absolute",
              right: 0,
              bottom: 0,
              width: "100%",
              borderTop: "1px solid #e9e9e9",
              padding: "10px 16px",
              background: "#fff",
              textAlign: "right",
            }}
          >
            <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>
              {"取消"}
            </Button>
            <Button
              type="primary"
              onClick={this.onHandleOk}
              loading={submitLoading}
            >
              {"确认"}
            </Button>
          </div>
        </Drawer>

        {/* 打印 */}
        <div id="print_table" style={{ display: "flex", display: "none" }}>
          {printData &&
            printData.list &&
            printData.list.map((it, i) => {
              return (
                <div
                  style={{
                    padding: 10,
                    width: "100%",
                    height: "100%",
                    margin: "auto",
                    position: "relative",
                  }}
                >
                  <div
                    style={{
                      fontSize: 30,
                      fontWeight: "bold",
                      textAlign: "center",
                      padding: 20,
                    }}
                  >
                    {locationData.batchNo} 版本{locationData.version}
                  </div>

                  <table width="100%" style={{ margin: "5px 0", fontSize: 14 }}>
                    <thead>
                      <tr
                        style={{
                          borderTop: "1px dashed #333",
                          borderBottom: "1px dashed #333",
                          fontWeight: "bold",
                        }}
                      >
                        <th
                          style={{
                            width: 30,
                            padding: "5px 0",
                            textAlign: "center",
                          }}
                        >
                          序号
                        </th>
                        <th>物料编码</th>
                        <th>物料规格</th>
                        <th>图号</th>
                        <th>机型</th>
                        <th>物料名称</th>
                        <th>数量</th>
                        <th>版本</th>
                        <th>仓库</th>
                        <th>装配组别名称</th>
                        <th>装配组别代码</th>
                        <th>依附关系和标准件</th>
                        <th>发料仓库</th>

                        
                        {/* <th style={{ width: 100 }}>物料编码</th>
                        <th style={{ width: 100 }}>物料规格</th>
                        <th style={{ width: 50 }}>图号</th>
                        <th>机型</th>
                        <th style={{ width: 100 }}>物料名称</th>
                        <th style={{ width: 40 }}>数量</th>
                        <th style={{ width: 40 }}>版本</th>
                        <th style={{ width: 100 }}>仓库</th>
                        <th style={{ width: 150 }}>装配组别名称</th>
                        <th style={{ width: 100 }}>装配组别代码</th>
                        <th style={{ width: 150 }}>依附关系和标准件</th>
                        <th style={{ width: 100 }}>发料仓库</th> */}
                      </tr>
                    </thead>
                    <tbody>
                      {it.map((item, index) => {
                        return (
                          <tr style={{ height: 15 }}>
                            <td style={{ textAlign: "center" }}>
                              {i * printData.pageNum + index + 1}
                            </td>
                            <td>{item.partCode}</td>
                            <td>{item.partSpec}</td>
                            <td>{item.paperCode}</td>
                            <td>{item.model}</td>
                            <td>{item.partName}</td>
                            <td style={{ textAlign: "center" }}>
                              {item.partNeedNum}
                            </td>
                            <td style={{ textAlign: "center" }}>
                              {item.version}
                            </td>
                            <td>{item.storeName}</td>
                            <td
                              style={{
                                maxWidth: 180,
                                overflow: "hidden",
                                whiteSpace: "nowrap",
                                textOverflow: "ellipsis",
                              }}
                            >
                              {item.assemblyGroup}
                            </td>
                            <td>{item.groupCode}</td>
                            <td
                              style={{
                                maxWidth: 200,
                                overflow: "hidden",
                                whiteSpace: "nowrap",
                                textOverflow: "ellipsis",
                              }}
                            >
                              {item.remark}
                            </td>
                            <td>{item.realityStoreName}</td>
                          </tr>
                        );
                      })}
                      <tr
                        style={{
                          height: 15,
                          borderTop: "1px dashed #333",
                        }}
                      >
                        <td colSpan={13}></td>
                      </tr>
                      {/* <tr
                        style={{
                          height: 15,
                          borderTop: "1px dashed #333",
                          borderBottom: "1px dashed #333",
                        }}
                      >
                        <td style={{ textAlign: "center", fontWeight: "bold" }}>
                          合计
                        </td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td style={{ textAlign: "center" }}>
                          {printData.numbers[i]}
                        </td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                      </tr> */}
                    </tbody>
                  </table>
                  <div style={{ textAlign: "center" }}>
                    第 {printData.pages[i] + 1} 页，共 {printData.pages.length}{" "}
                    页
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    );
  }
}
export default Form.create()(withRouter(Bom_details));
